package com.javaweb.base;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.time.Duration;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import javax.sql.DataSource;

import org.hibernate.validator.HibernateValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.ScanOptions.ScanOptionsBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import com.javaweb.base.po.User;
import com.javaweb.config.datasource.common.IdGenerator;
import com.javaweb.config.minio.MinioParameter;
import com.javaweb.constant.CommonConstant;
import com.javaweb.constant.SystemConstant;
import com.javaweb.constant.SystemConstant.AdminConstant;
import com.javaweb.constant.SystemConstant.DataSourceConstant;
import com.javaweb.constant.SystemConstant.HeadConstant;
import com.javaweb.constant.SystemConstant.LoginConstant;
import com.javaweb.constant.SystemConstant.RedisConstant;
import com.javaweb.context.ApplicationContextHelper;
import com.javaweb.enums.HttpCodeEnum;
import com.javaweb.util.core.SecretUtil;
import com.javaweb.util.core.StringUtil;
import com.javaweb.web.eo.TokenData;

import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;

/**
 * 基础注入类
 * <p>
 * 本类中全部为set注入，一般有三种形式的注入（属性@Autowired注入、set注入、构造方法注入）
 * @author tank2140896
 */
public class BaseInject {
	
	/**
	 * slf4j日志
	 */
	public final Logger log = LoggerFactory.getLogger(getClass());
	
	/* -------------------------------------------------- 分界线 -------------------------------------------------- */
	
	/**
	 * record不可变类
	 */
	record FinalUser(String userId,String userName,String password) {}
	
	/**
	 * 获取管理员
	 * @return User 用户信息
	 */
	public User getAdminUser() {
		var finalUser = new FinalUser(AdminConstant.ADMIN_USER_ID,AdminConstant.ADMIN_USER_NAME,AdminConstant.ADMIN_PASSWORD);
		var date = new Date();
		var user = new User();
		user.setUserId(finalUser.userId());//改造代码时不建议修改此值
		user.setUserName(finalUser.userName());//改造代码时可以修改
		user.setPassword(finalUser.password());//改造代码时强烈建议修改
		user.setPersonName("管理员");//改造代码时可以修改
		user.setLevel(CommonConstant.ZERO_NUMBER_VALUE);//改造代码时不建议修改此值
		user.setRemark("管理员，该账号无法被删除，即使删除也会被恢复");//改造代码时可以修改
		user.setStatus(CommonConstant.ZERO_NUMBER_VALUE);//改造代码时不建议修改此值
		user.setFirstLoginDate(date);
		user.setLastLoginDate(date);
		user.setCreator(AdminConstant.ADMIN_USER_ID);//改造代码时不建议修改此值
		user.setCreateDate(date);//改造代码时不建议修改此值
		user.setUpdater(AdminConstant.ADMIN_USER_ID);//改造代码时不建议修改此值
		user.setUpdateDate(date);//改造代码时不建议修改此值
		user.setDelFlag(CommonConstant.ZERO_NUMBER_VALUE);//改造代码时不建议修改此值
		return user;
	}
	
	/* -------------------------------------------------- 分界线 -------------------------------------------------- */
	
	/**
	 * RequestMappingHandlerMapping
	 */
	public RequestMappingHandlerMapping requestMappingHandlerMapping;
	
    /**
     * RequestMappingHandlerMapping的set方法
     * @param requestMappingHandlerMapping RequestMappingHandlerMapping
     */
	@Autowired
	public void setRequestMappingHandlerMapping(RequestMappingHandlerMapping requestMappingHandlerMapping) {
		this.requestMappingHandlerMapping = requestMappingHandlerMapping;
	}
	
	/**
	 * 主键ID生成器
	 */
	public IdGenerator idGenerator;
	
    /**
     * 主键ID生成器的set方法
     * @param idGenerator IdGenerator
     */
	@Autowired
	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}
	
	/**
	 * Environment
	 */
	public Environment environment;
	
    /**
     * Environment的set方法
     * @param environment Environment
     */
	@Autowired
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}
	
	/**
	 * MessageSource
	 */
	public MessageSource messageSource;
	
    /**
     * MessageSource的set方法
     * @param messageSource MessageSource
     */
	@Autowired
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}
	
	/**
	 * 数据源D1的JdbcTemplate
	 */
	public JdbcTemplate mysqlD1JdbcTemplate;
	
    /**
     * 数据源D1的JdbcTemplate的set方法
     * @param mysqlD1JdbcTemplate JdbcTemplate
     */
	@Autowired
	@Qualifier(DataSourceConstant.DATA_SOURCE_D1_JDBCTEMPLATE)
	public void setMysqlD1JdbcTemplate(JdbcTemplate mysqlD1JdbcTemplate) {
		this.mysqlD1JdbcTemplate = mysqlD1JdbcTemplate;
	}
	
	/**
	 * 数据源D2的JdbcTemplate
	 */
	public JdbcTemplate mysqlD2JdbcTemplate;
	
    /**
     * 数据源D2的JdbcTemplate的set方法
     * @param mysqlD2JdbcTemplate JdbcTemplate
     */
	@Autowired
	@Qualifier(DataSourceConstant.DATA_SOURCE_D2_JDBCTEMPLATE)
	public void setMysqlD2JdbcTemplate(JdbcTemplate mysqlD2JdbcTemplate) {
		this.mysqlD2JdbcTemplate = mysqlD2JdbcTemplate;
	}
	
	/**
	 * 数据源D1的MysqlDateSource1
	 */
	public DataSource mysqlDateSource1;
	
    /**
     * 数据源D1的MysqlDateSource1的set方法
     * @param DataSource MysqlDateSource1
     */
	@Autowired
	@Qualifier(DataSourceConstant.DATA_SOURCE_KEY_1)
	public void setMysqlDateSource1(DataSource mysqlDateSource1) {
		this.mysqlDateSource1 = mysqlDateSource1;
	}
	
	/**
	 * 数据源D2的MysqlDateSource2
	 */
	public DataSource mysqlDateSource2;
	
    /**
     * 数据源D2的MysqlDateSource2的set方法
     * @param DataSource MysqlDateSource2
     */
	@Autowired
	@Qualifier(DataSourceConstant.DATA_SOURCE_KEY_2)
	public void setMysqlDateSource2(DataSource mysqlDateSource2) {
		this.mysqlDateSource2 = mysqlDateSource2;
	}
	
	/**
	 * 获取连接
	 * @param dataSource DataSource
	 * @return Connection 数据库连接
	 */
	public Connection getConnection(DataSource dataSource) {
        return DataSourceUtils.getConnection(dataSource);
	}
	
	/**
	 * 关闭连接
	 * @param connection Connection
	 * @param dataSource DataSource
	 */
	public void closeConnection(Connection connection,DataSource dataSource) {
		DataSourceUtils.releaseConnection(connection,dataSource);
	}
	
	/**
	 * StringRedisTemplate
	 */
	public StringRedisTemplate stringRedisTemplate;
	
    /**
     * StringRedisTemplate的set方法
     * @param stringRedisTemplate StringRedisTemplate
     */
	@Autowired
	@Qualifier("redisTemplate")
	public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
		this.stringRedisTemplate = stringRedisTemplate;
	}
	
	/**
	 * ValueOperations
	 */
	public ValueOperations<Object,Object> valueOperations;
	
    /**
     * ValueOperations的set方法
     * @param valueOperations ValueOperations<Object,Object>
     */
	@Resource(name="redisTemplate")
	public void setValueOperations(ValueOperations<Object,Object> valueOperations) {
		this.valueOperations = valueOperations;
	}
	
	/* -------------------------------------------------- 分界线 -------------------------------------------------- */
	
	/**
	 * 静态BeanFactory
	 */
	private static BeanFactory beanFactory = null;
	
	/**
	 * 获取BeanFactory
	 * @return BeanFactory beanFactory
	 */
	public static BeanFactory getBeanFactory(HttpServletRequest request) {
		if(beanFactory==null) {
			beanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
		}
		return beanFactory;
	}
	
	/**
	 * 静态RedisTemplate
	 */
	private static RedisTemplate<String,Object> staticRedisTemplate = null;
	
	/**
	 * 获取RedisTemplate，适用于无法通过注入获得RedisTemplate的地方
	 * @return RedisTemplate RedisTemplate
	 */
	@SuppressWarnings("unchecked")
	public static RedisTemplate<String,Object> getRedisTemplate() {
		if(staticRedisTemplate==null){
			//RedisTemplate redisTemplate = (RedisTemplate)getBeanFactory(request.getServletContext()).getBean(SystemConstant.REDIS_TEMPLATE);
			staticRedisTemplate = (RedisTemplate<String,Object>)ApplicationContextHelper.getBean(RedisConstant.REDIS_TEMPLATE);
		}
		return staticRedisTemplate;
	}
	
	/**
	 * 静态Environment
	 */
	private static Environment staticEnvironment = null;
	
	/**
	 * 获取Environment，适用于无法通过注入获得Environment的地方
	 * @return Environment Environment
	 * @see com.javaweb.context.ApplicationContextHelper
	 */
	public static Environment getEnvironment() {
		if(staticEnvironment==null){
			staticEnvironment = (Environment)ApplicationContextHelper.getBean(SystemConstant.ENVIRONMENT);
		}
		return staticEnvironment;
	}
	
	/* -------------------------------------------------- 分界线 -------------------------------------------------- */
	
	/**
	 * 获取所有redis中的key总数
	 * @return long 所有redis中的key总数
	 */
	public long getAllRedisKeys() {
		return stringRedisTemplate.getConnectionFactory().getConnection().commands().dbSize();
	}
	
	/**
	 * 查询redis的key
	 * @param key key值（如：*a*）
	 * @param totalCount 总共要输出多少记录（如果传<=0，则表示查出所有）
	 * @return Set<String> redis的key集合
	 */
	public Set<String> redisKeySearch(String key,long totalCount) {
		return stringRedisTemplate.execute((RedisCallback<Set<String>>) connection -> {
			Set<String> binaryKeys = new HashSet<>();
			ScanOptionsBuilder scanOptionsBuilder = ScanOptions.scanOptions().match(key);
			if(totalCount>0) {
				scanOptionsBuilder.count(totalCount);
			}
            Cursor<byte[]> cursor = connection.commands().scan(scanOptionsBuilder.build());
            while(cursor.hasNext()) {
                binaryKeys.add(new String(cursor.next()));
            }
            return binaryKeys;
		});
	}
	
	/**
	 * 将key和value映射到redis中去
	 * @param key key值
	 * @param value value值
	 * @param duration 失效时间（传null则表示在内存中永不失效）
	 */
	public void setDataToRedis(String key,Object value,Duration duration) {
		if(duration==null){
			valueOperations.set(key,value);
		}else{
			valueOperations.set(key,value,duration);
		}
	}
	
	/**
	 * 将key和value映射到redis中去（静态方法）
	 * @param key key值
	 * @param value value值
	 * @param duration 失效时间（传null则表示在内存中永不失效）
	 */
	public static void staticSetDataToRedis(String key,Object value,Duration duration) {
		RedisTemplate<String,Object> currentRedisTemplate = getRedisTemplate();
		if(duration==null){
			currentRedisTemplate.opsForValue().set(key,value);
		}else{
			currentRedisTemplate.opsForValue().set(key,value,duration);
		}
	}
	
	/**
	 * 根据key值获取value值
	 * @param key key值
	 * @return Object value值
	 */
	public Object getDateFromRedisByKey(String key) {
		return valueOperations.get(key);
	}
	
	/**
	 * 根据key值删除value值
	 * @param key key值
	 * @return boolean 是否删除成功（true：删除成功；false：删除失败）
	 */
	public Boolean deleteFromRedisByKey(String key) {
		return stringRedisTemplate.delete(key);
	}
	
	/**
	 * 根据key值获取value值（静态）
	 * @param key key值
	 * @return Object value值
	 */
	public static Object getDateFromRedisTemplateByKey(String key) {
		return getRedisTemplate().opsForValue().get(key);
	}
	
	/**
	 * 获取token的key值
	 * <p>
	 * redis的token的key增加个前缀，关联BaseInject#getTokenData和OnlineUserController#list
	 * @param tokenData TokenData
	 * @return String token的key值（key值组成为：userId,clientType,loginWay）
	 */
	public static String getRedisTokenKey(TokenData tokenData) {
		return  LoginConstant.TOKEN_KEY_PREFIX + 
				tokenData.getUser().getUserId() + CommonConstant.COMMA + 
				tokenData.getClientType() + CommonConstant.COMMA + 
				tokenData.getLoginWay();
	}
	
	/**
	 * 根据用户ID删除用户登录信息
	 * <p>
	 * 将删除所有用户端的登录信息
	 * @param userId 用户ID
	 */
	public static void deleteRedisTokenKeyByUserId(String userId) {
		Set<String> set = getRedisTemplate().keys(LoginConstant.TOKEN_KEY_PREFIX+userId+"*");
		getRedisTemplate().delete(set);
	}
	
	/**
	 * 解密token获取TokenData
	 * <p>
	 * redis的token的key增加个前缀，关联BaseInject#getRedisTokenKey和OnlineUserController#list
	 * @param token 加密的token
	 * @return TokenData TokenData
	 */
	public static TokenData getTokenData(String token) {
		TokenData tokenData = null;
		if(token!=null) {
			try{
				token = SecretUtil.base64DecoderString(token,StandardCharsets.UTF_8);
				token = SecretUtil.decryptAes(token,LoginConstant.TOKEN_AES_KEY);
		    	String tokens[] = token.split(CommonConstant.COMMA);
		    	token = tokens[1]+CommonConstant.COMMA+tokens[2]+CommonConstant.COMMA+tokens[3];//userId,clientType,loginWay
		    	tokenData = (TokenData)(getRedisTemplate().opsForValue().get(LoginConstant.TOKEN_KEY_PREFIX + token));
			}catch(Exception e) {
				//do nothing
			}
		}
		return tokenData;
	}
	
	/* -------------------------------------------------- 分界线 -------------------------------------------------- */

	/**
	 * 根据消息key值获取配置文件信息的消息value值
	 * @param messageKey 消息key值
	 * @return String 消息value值
	 */
	public String getMessage(String messageKey) {
		try {
			return messageSource.getMessage(messageKey,null,LocaleContextHolder.getLocale());
		} catch(Exception e) {
			return messageKey;
		}
	}
	
	/**
	 * 根据消息key值获取配置文件信息的消息value值（供国际化使用）
	 * @param messageKey 消息key值
	 * @param request HttpServletRequest
	 * @return String 消息value值
	 * @see com.javaweb.config.i18n.I18NConfig
	 */
	public String getMessage(String messageKey,HttpServletRequest request) {
		String acceptLanguage = request.getHeader("Accept-Language");
		if(StringUtil.isEmpty(acceptLanguage)) {
			return getMessage(messageKey);
		}
		try {
			String[] splits = acceptLanguage.split(CommonConstant.UNDERLINE);
			return messageSource.getMessage(messageKey,null,Locale.of(splits[0],splits[1]));
		} catch(Exception e) {
			return messageKey;
		}
	}
	
	/**
	 * 获取校验错误信息
	 * @param bindingResult BindingResult
	 * @return String 错误信息
	 */
	public String getValidateMessage(BindingResult bindingResult) {
		List<ObjectError> list = bindingResult.getAllErrors();
		if(CollectionUtils.isEmpty(list)) {
			return CommonConstant.EMPTY_VALUE;
		}
		return getMessage(list.get(0).getDefaultMessage());
	}
	
	/**
	 * 信息返回
	 * @param httpCodeEnum Http状态码枚举
	 * @param messageKey 消息key值
	 * @param data 数据
	 * @return BaseResponseResult 信息返回体
	 */
	public BaseResponseResult SUCCESS(String messageKey,Object data) {
		return new BaseResponseResult(HttpCodeEnum.SUCCESS,getMessage(messageKey),data);
	}
	
	/**
	 * 信息返回
	 * @param httpCodeEnum Http状态码枚举
	 * @param messageKey 消息key值
	 * @param data 数据
	 * @return BaseResponseResult 信息返回体
	 */
	public BaseResponseResult getBaseResponseResult(HttpCodeEnum httpCodeEnum,String messageKey,Object data) {
		return new BaseResponseResult(httpCodeEnum.getCode(),getMessage(messageKey),data);
	}
	
	/**
	 * 信息返回
	 * @param httpCodeEnum Http状态码枚举
	 * @param messageKey 消息key值
	 * @return BaseResponseResult 信息返回体
	 */
	public BaseResponseResult getBaseResponseResult(HttpCodeEnum httpCodeEnum,String messageKey) {
		return getBaseResponseResult(httpCodeEnum,messageKey,CommonConstant.NULL_VALUE); 
	}
	
	/**
	 * 信息返回
	 * @param httpCodeEnum  Http状态码枚举
	 * @param bindingResult BindingResult
	 * @param data 数据
	 * @return BaseResponseResult 信息返回体
	 */
	public BaseResponseResult getBaseResponseResult(HttpCodeEnum httpCodeEnum,BindingResult bindingResult,Object data) {
		return new BaseResponseResult(httpCodeEnum.getCode(),this.getValidateMessage(bindingResult),data);
	}
	
	/**
	 * 信息返回
	 * @param httpCodeEnum Http状态码枚举
	 * @param bindingResult BindingResult
	 * @return BaseResponseResult 信息返回体
	 */
	public BaseResponseResult getBaseResponseResult(HttpCodeEnum httpCodeEnum,BindingResult bindingResult) {
		return getBaseResponseResult(httpCodeEnum,bindingResult,CommonConstant.NULL_VALUE);
	}
	
	/* -------------------------------------------------- 分界线 -------------------------------------------------- */
	
	/**
	 * 获取token
	 * @param httpServletRequest HttpServletRequest
	 * @return String token
	 */
	public static String getToken(HttpServletRequest httpServletRequest) {
		//1、支持header传参方式
		String token = httpServletRequest.getHeader(HeadConstant.HEAD_TOKEN);
		if(token==null) {
			//2、支持问号传参方式
			token = httpServletRequest.getParameter(HeadConstant.HEAD_TOKEN);
		}
		return token;
	}
	
	/**
	 * 获取token
	 * @param nativeWebRequest NativeWebRequest
	 * @return String token
	 */
	public static String getToken(NativeWebRequest nativeWebRequest) {
		//1、支持header传参方式
		String token = nativeWebRequest.getHeader(HeadConstant.HEAD_TOKEN);
		if(token==null) {
			//2、支持问号传参方式
			token = nativeWebRequest.getParameter(HeadConstant.HEAD_TOKEN);
		}
		return token;
	}
	
	/**
	 * 获取token
	 * @param serverHttpRequest ServerHttpRequest
	 * @return String token
	 */
	public static String getToken(ServerHttpRequest serverHttpRequest) {
		//1、支持header传参方式
		String token = serverHttpRequest.getHeaders().getFirst(HeadConstant.HEAD_TOKEN);
		if(token==null) {
			try{
				//2、支持问号传参方式
				token = serverHttpRequest.getURI().getPath();
				token = token.split(HeadConstant.HEAD_TOKEN + CommonConstant.EQUAL)[1].split(CommonConstant.AND)[0];
			}catch(Exception e) {
				//do nothing
			}
		}
		return token;
	}
	
	/* -------------------------------------------------- 分界线 -------------------------------------------------- */
	
	/**
	 * 快速校验
	 */
	public static final Validator FAST_VALIDATOR = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
	
	/**
	 * 全部校验
	 */
	public static final Validator ALL_VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

	/**
	 * 快速校验
	 * @param t 校验参数
	 * @return List<String> 错误信息列表 
	 */
	public static <T> List<String> fastFailValidate(T t) {
		List<String> errorMessages = new LinkedList<String>();
		Set<ConstraintViolation<T>> constraintViolations = FAST_VALIDATOR.validate(t);
        if(constraintViolations!=null&&constraintViolations.size()>0){
        	//constraintViolations.iterator().next().getPropertyPath().toString()
        	errorMessages.add(constraintViolations.iterator().next().getMessage());
        }
        return errorMessages;
    }
	
	/**
	 * 全部交验
	 * @param t 校验参数
	 * @return List<String> 错误信息列表 
	 */
	public static <T> List<String> allCheckValidate(T t) {
		List<String> errorMessages = new LinkedList<String>();
        Set<ConstraintViolation<T>> constraintViolations = ALL_VALIDATOR.validate(t);
        if(constraintViolations!=null&&constraintViolations.size()>0) {
            Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
            while(iterator.hasNext()){
                ConstraintViolation<T> violation = iterator.next();
                //violation.getPropertyPath().toString()
                errorMessages.add(violation.getMessage());
            }
        }
        return errorMessages;
	}
	
	/* -------------------------------------------------- 分界线 -------------------------------------------------- */
	
	
	/**
	 * Minio参数
	 */
	private MinioParameter minioParameter;
	
    
    /**
     * MinioParameter的set方法
     * @param minioParameter MinioParameter
     */
	@Autowired
	public void setMinioParameter(MinioParameter minioParameter) {
		this.minioParameter = minioParameter;
	}
	
	/**
	 * Minio客户端对象
	 */
	private MinioClient minioClient = null;
	
	/**
	 * 获取Minio客户端
	 * @return MinioClient Minio客户端
	 */
	public MinioClient getMinioClient() {
		if(minioClient==null) {
			minioClient = MinioClient.builder().endpoint(minioParameter.getEndpoint()).credentials(minioParameter.getUsername(),minioParameter.getPassword()).build();
		}
		return minioClient;
	}
	
	/**
	 * Minio上传文件
	 * @param name 文件名称
	 * @param inputStream 输入流
	 * @return ObjectWriteResponse ObjectWriteResponse
	 * @throws Exception 异常
	 */
	public ObjectWriteResponse uploadFileByMinio(String name,InputStream inputStream) throws Exception {
		MinioClient minioClient = this.getMinioClient();
		String buctet = minioParameter.getBucket();
		boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(buctet).build());
        if(!isExist){
        	minioClient.makeBucket(MakeBucketArgs.builder().bucket(buctet).build());
        }
        PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(buctet).object(name).stream(inputStream,-1,5*1024*1024).contentType("application/octet-stream").build();
		ObjectWriteResponse objectWriteResponse = minioClient.putObject(putObjectArgs);
		return objectWriteResponse;
	}
	
	/**
	 * Minio下载文件
	 * @param name 文件名称
	 * @return InputStream 输入流
	 * @throws Exception 异常
	 */
	public InputStream downloadFileByMinio(String name) throws Exception {
		MinioClient minioClient = this.getMinioClient();
		GetObjectArgs getObjectArgs = GetObjectArgs.builder().bucket(minioParameter.getBucket()).object(name).build();
		InputStream inputStream = minioClient.getObject(getObjectArgs);
		return inputStream;
	}
	
	/**
	 * Minio删除文件
	 * @param name 文件名称
	 * @throws Exception 异常
	 */
	public void deleteFileByMinio(String name) throws Exception {
		MinioClient minioClient = this.getMinioClient();
		RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(minioParameter.getBucket()).object(name).build();
		minioClient.removeObject(removeObjectArgs);
	}
	
	/* -------------------------------------------------- 分界线 -------------------------------------------------- */

}